<template>
  <div>
    <el-form ref="formRef" label-width="100px" :model="form" :rules="rules">
      <el-form-item label="部门名称">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="部门编码">
        <el-input v-model="form.code" />
      </el-form-item>
      <el-form-item label="部门负责人">
        <el-select v-model="form.manager" placeholder="请选择负责人">
          <el-option
            v-for="item in list"
            :key="item.id"
            :value="item.username"
            :label="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍">
        <el-input v-model="form.introduce" />
      </el-form-item>
      <el-form-item style="text-align:center">
        <el-button>取消</el-button>
        <el-button type="primary" @click="submitDepartment">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { simpleUser, addDepartment, edit, departmentInfo } from '@/api/department'
export default {
  props: {
    id: {
      type: String,
      required: true
    },
    edit: {
      type: Boolean,
      required: true
    }
  },
  data() {
    const validName = function(rules, value, callback) {
      console.log(value)
    }
    const validCode = function(rules, value, callback) {
      console.log(value)
    }
    return {
      rules: {
        name: [{ required: true, message: '请输入用户名', trigger: blur },
          { validator: validName, message: '请输入用户名', trigger: blur }],
        code: [{ required: true, message: '请输入用户名', trigger: blur },
          { validator: validCode, message: '请输入用户名', trigger: blur }]
      },
      form: {
        name: '',
        introduce: '',
        manager: '',
        code: ''
      },
      // 负责人名单
      list: []
    }
  },
  created() {
    this.getSimpleUser()
  },
  methods: {
    // 获取负责人名称，发送ajax获得简单人员信息
    async getSimpleUser() {
      const res = await simpleUser()
      this.list = res.data.data
    },
    async submitDepartment() {
      if (this.edit) {
        this.editDepartment()
        this.$emit('success')
      } else {
        // 添加部门发送ajax
        await addDepartment({ ...this.form, pid: this.id })
        // 添加成功后，把函数传回父组件，控制弹框消息，并更新页面
        this.$emit('success')
      }
    },
    // 编辑信息时，把原信息渲染到弹窗
    async getDepartmentInfo() {
      const res = await departmentInfo(this.id)
      this.form = res.data.data
    },
    // 发送编辑部门的ajax
    async editDepartment() {
      await edit(this.form)
    },
    // 清空表格
    clear() {
      // this.$refs.formRef.resetFields()
      this.form.name = ''
      this.form.introduce = ''
      this.form.manager = ''
      this.form.code = ''
    }
  }
}
</script>

<style>

</style>
